package leetcode;

/**
 * Created by Ghost on 2014/10/20 0020.
 */
public class Remove_Nth_Node_From_End_of_List {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if(n<=0)
            return head;
        ListNode slow = head;
        ListNode fast = head;
        int i = 0;
        while(i<n && fast!=null){
            fast = fast.next;
            i++;
        }
        if(i==n && fast == null){
            return slow.next;
        }
        else if(i<n && fast == null)
            return head;
        else{
            while(fast.next!=null){
                slow = slow.next;
                fast = fast.next;
            }
            slow.next = slow.next.next;
        }
        return head;
    }
    public static void main(String[] args){
        Remove_Nth_Node_From_End_of_List remove_nth_node_from_end_of_list = new Remove_Nth_Node_From_End_of_List();
        ListNode listNode = new ListNode(1);
        listNode.next = new ListNode(2);
        listNode.next.next = new ListNode(3);
//      listNode.next.next.next = new ListNode(4);
        ListNode head = remove_nth_node_from_end_of_list.removeNthFromEnd(listNode, 1);
        while(head!=null){
            System.out.println(" "+head.val);
            head = head.next;
        }

    }
}
